#coding:utf-8

from twisted.internet import reactor, defer, threads
from twisted.internet.protocol import Protocol, Factory, DatagramProtocol

#import report
import stock
import sys, os, time
import datamethod as dm
import buss
import pickle
import datetime
import report

SERVER_TELNUMBER = [0x30, 0x39, 0x35, 0x30, 0x30] +[0x20] * 10
SERVER_AREACODE = [0x52, 0x7f]
SERVER_VERSION = [0x00]
class BaseDataDeal:
    def logon_old(self, data, *args):
        pass
        
    def logon(self, data, *args):
        data = dm.pickUps(data)
        for i in range(data.get(1)):
            arg = data.get(1)
            if arg == 0x01:
                tel = data.get(data.get(1))
            elif arg == 0x02:
                version = data.get(data.get(1))
        self.logonRequest(dm.data2asc(tel).strip(), *args)
    
    def recvdBuss(self, data, *args):
        checksum = dm.getchecksum_buss(data[:-1]) # 业务数据末尾校验和比较
        if  not data[-1] == checksum:
            report.error(u'%s业务校验和:[e:%d]'%(dm.data2str(data), checksum))
        self.bussDataReceived(data[3:-1], *args)
         
    def recvdLink(self, data, *args):
        if data:
            report.error(u"链路维护应答内部含有数据:%s"%data)
        self.linkReceived(None, *args)
        
    def logout(self, data, *args):
        data = dm.pickUps(data)
        for i in range(data.get(1)):
            if data.get(1) == 0x01:
                tel = data.get(data.get(1))
        if not tel == self.tel:
            report.error(u"未知车辆%s要求登出[should:%s]"%(dm.data2asc(tel), self.strtel))
        self.logoutRequest(dm.data2asc(tel).strip(), *args)
        
    def _check_checksum(self, data): # 除去7e头尾后的完整数据
        get = data[0]
        calc = dm.getchecksum(data[1:])
        if get != calc:
            report.error(u"校验和错误:%s[e:%d,r:%d]"%(dm.data2str(data), calc, get))
        return data[1:]
    
    def separate_data(self, data, *args):
        """检验校验和,分离出用户数据.返回(优先级,数据类型,用户数据)"""
        data = self._check_checksum(data)
        if not data: return None
        priority, type = data[0], data[1]
        data = data[2:]
        
        if type == 0x01:
            return  self.logon_old(data, *args)
        elif type == 0x11:
            return  self.logon(data, *args)
        elif type == 0x02:
            return  self.recvdBuss(data, *args)
        elif type == 0x04:
            self.recvdLink(data, *args)
        elif type == 0x12:
            return  self.logout(data, *args)
        else:
            return None #如果没有方法?


if __name__ == '__main__':
    import sys, os
    mainDir = os.path.dirname(os.getcwd())
    sys.path.append(mainDir)
    a = ConfigIni()
    print a.get('TCP','we')